package com.example.takeaway.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.takeaway.common.ResponseEnum;
import com.example.takeaway.context.UserInfoContext;
import com.example.takeaway.converter.SpecificationConverter;
import com.example.takeaway.exception.BusException;
import com.example.takeaway.mapper.DishItemSpecificationMapper;
import com.example.takeaway.mapper.SpecificationMapper;
import com.example.takeaway.model.PageVO;
import com.example.takeaway.model.bo.Specification;
import com.example.takeaway.model.dto.SpecificationDTO;
import com.example.takeaway.model.dto.SpecificationEditorDTO;
import com.example.takeaway.model.vo.SpecificationVO;
import com.example.takeaway.service.SpecificationService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 规格表 服务实现类
 * </p>
 *
 * @author 邢晨旭
 * @since 2023-10-12
 */
@Service
public class SpecificationServiceImpl extends ServiceImpl<SpecificationMapper, Specification> implements SpecificationService {

    @Resource
    SpecificationConverter converter;

    @Resource
    DishItemSpecificationMapper dishItemSpecificationMapper;

    @Override
    public void addSpecification(SpecificationDTO param) {
        baseMapper.insert(converter.toSpecification(param));
    }

    @Override
    public void updateSpecificationById(SpecificationEditorDTO param) {
        baseMapper.updateById(converter.toSpecification(param));
    }

    @Override
    public SpecificationVO queryById(Long id) {
        Specification specification = baseMapper.selectById(id);
        if (specification == null || specification.getIsDeleted() == 1) {
            throw new BusException(ResponseEnum.SPECIFICATION_NOT_FOUND);
        }
        return converter.toSpecificationVO(specification);
    }

    @Override
    public void deleteById(Long id) {
        //关联的有菜品就不能删除
        Integer count = dishItemSpecificationMapper.countDishBySpecificationId(id);
        if (count > 0) {
            throw new BusException(ResponseEnum.SPECIFICATION_CANNOT_DELETE);
        }
        //删除规格
        baseMapper.deleteSpecificationById(id);
    }

    @Override
    public PageVO<SpecificationVO> queryPage(Integer page, Integer size) {
        Page<Specification> pageDTO = PageDTO.of(page, size);
        List<Specification> list = baseMapper.queryPage(pageDTO, UserInfoContext.get().getUserId());
        PageVO<SpecificationVO> pageVO = new PageVO<>();
        pageVO.setPage(page);
        pageVO.setSize(size);
        pageVO.setTotal(pageDTO.getTotal());
        pageVO.setList(converter.toSpecificationVO(list));
        return pageVO;
    }

    @Override
    public List<SpecificationVO> queryList() {
        return baseMapper.queryList(UserInfoContext.get().getUserId());
    }
}
